# reset_db.py
import os
import sys
import django
from django.core import management
from django.conf import settings
from django.db import connections,connection, OperationalError

def reset_database():
    # 配置Django环境
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
    django.setup()
    # 在django.setup()后添加：
    try:
        connection.ensure_connection()
    except OperationalError:
        print("❌ 数据库连接失败，请检查local_settings配置")
        sys.exit(1)

    # 删除所有迁移文件（保留__init__.py）
    migrations_dir = os.path.join(settings.BASE_DIR, 'app01/migrations')
    for fname in os.listdir(migrations_dir):
        if fname.endswith('.py') and fname != '__init__.py':
            os.remove(os.path.join(migrations_dir, fname))

    # 根据数据库类型执行重置
    db_config = settings.DATABASES['default']
    if db_config['ENGINE'] == 'django.db.backends.sqlite3':
        # SQLite处理
        if os.path.exists(db_config['NAME']):
            os.remove(db_config['NAME'])
    else:  # MySQL/PostgreSQL
        # 获取原生连接
        with connections['default'].cursor() as cursor:
            db_name = db_config['NAME']
            print(f'Dropping database {db_name}...')
            cursor.execute(f'DROP DATABASE {db_name}')
            cursor.execute(f'CREATE DATABASE {db_name}')

    # 重新生成迁移文件
    management.call_command('makemigrations')
    
    # 执行迁移
    management.call_command('migrate')
    
    # 创建超级用户（可选）
    management.call_command('createsuperuser', 
                          email='15358806112@189.cn',
                          username='chad',
                          interactive=False)

if __name__ == '__main__':
    print('⚠️ 即将删除整个数据库！请确认已备份重要数据！')
    confirm = input('确定继续吗？(y/n): ')
    if confirm.lower() == 'y':
        reset_database()
        print('✅ 数据库重置完成')
    else:
        print('❌ 操作已取消')